#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <stdio.h>

LRESULT CALLBACK WndProc(HWND winProcHnd, UINT msg, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{ 
  const char* lpszClassName = "My Demo Class";
  const char* lpszWindowCaption = "My Demo Window";
  
  WNDCLASS wc;
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = WndProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = hInstance;
  wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
  wc.lpszMenuName = NULL;
  wc.lpszClassName = lpszClassName;

  RegisterClass(&wc);
  
  HWND hWnd = CreateWindow(
    lpszClassName,        // LPCTSTR lpClassName,
    lpszWindowCaption,    // LPCTSTR lpWindowName,
    WS_OVERLAPPEDWINDOW,  // DWORD dwStyle,
    0,                    // int x,
    0,                    // int y,
    640,                  // int nWidth,
    480,                  // int nHeight,
    NULL,                 // HWND hWndParent,
    NULL,                 // HMENU hMenu,
    hInstance,            // HINSTANCE hInstance,
    NULL                  // LPVOID lpParam
    );
    
  ShowWindow(hWnd, SW_SHOW);
  
  // Message Loop.
  MSG msg;
  while (GetMessage(&msg, NULL, 0, 0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
  }
  
  return 0;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{  
  static bool hasClick = false;
  static int x, y;
  PAINTSTRUCT ps;  
  HDC hDC;
  RECT rect;
  
  char buf[1024];
  switch (msg) {
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
      
    case WM_PAINT:
      hDC = BeginPaint(hWnd, &ps);
      if (hasClick) {        
        rect.left = x; 
        rect.top = y;
        rect.right = x + 100;
        rect.bottom = y + 100;
        FillRect(hDC, &rect, (HBRUSH)(GRAY_BRUSH));
      }        
      EndPaint(hWnd, &ps);
      break;
      
    case WM_LBUTTONDOWN:      
      x = GET_X_LPARAM(lParam); 
      y = GET_Y_LPARAM(lParam);
      sprintf(buf, "%d, %d", x, y);
      hasClick = true;
      InvalidateRect(hWnd, NULL, true);
      //MessageBox(hWnd, buf, "Error", MB_OK);
      break;
      
    default: 
      return DefWindowProc(hWnd, msg, wParam, lParam);     
      break;
  }
  return 0;  
}
